package com.zdc.learn.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * nio server
 */
public class NioServer {

    private ServerSocketChannel serverSocketChannel = null;

    private  Selector selector = null;


    public NioServer(){
        try {
            //得到 ServerSocketChannel
            serverSocketChannel = ServerSocketChannel.open();

            //获取选择器
            selector = Selector.open();

            //指定端口号
            InetSocketAddress address = new InetSocketAddress(6666);

            //绑定端口号
            serverSocketChannel.socket().bind(address);
            //设置非阻塞
            serverSocketChannel.configureBlocking(false);

            //注册
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception{

        NioServer nioServer = new NioServer();
        nioServer.serverListen();
    }


    private void serverListen(){
        //线程监听
        while (true){
            try {
                int count = selector.select();
                //>0 有事件处理
                if (count > 0){
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        //取出selectionkey
                        SelectionKey key = iterator.next();
                        //有客户端进来
                        if (key.isAcceptable()){
                            System.out.println("有人来啦。。。。。。。。。。。。。。。");
                            SocketChannel sc = serverSocketChannel.accept();
                            sc.configureBlocking(false);
                            //注册到selector上
                            sc.register(selector,SelectionKey.OP_READ);

                            //提示
                            System.out.println(sc.getRemoteAddress()+"上线");
                        }
                        if (key.isReadable()){
                            getMsg(key);
                        }

                        iterator.remove();
                    }
                }else {
                    System.out.println("等待。。。。。。。。。。。");
                }
            }catch (Exception e){

            }

        }
    }

    //得到消息
    private void getMsg(SelectionKey key){
            SocketChannel channel = null;
            try{
                channel = (SocketChannel) key.channel();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int read = channel.read(byteBuffer);
                if (read >0){
                    String msg = new String(byteBuffer.array());
                    System.out.println("from 客户端："+msg);
                    sendToclient(msg,channel);
                }

            }catch (Exception e){
                e.printStackTrace();
            }

//        try{
//            SocketChannel channel = (SocketChannel) key.channel();
//
//            //设置buffer
//            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//            channel.configureBlocking(false);
//            //从channel中读取获取字节流 buffer
//            int read = channel.read(byteBuffer);
//            if (read > 0){
//                //将缓存区的数据转换成字符串
//                String msg = new String(byteBuffer.array());
//                System.out.println("from 客户端："+msg);
//                for (SelectionKey key1:selector.keys()){
//                    Channel ch = key.channel();
//                    if (ch instanceof  SocketChannel){
//                            System.out.println("@@@@@@@@@@:"+(ch != channel));
//                        SocketChannel sc = (SocketChannel) ch;
//                        ByteBuffer bb = ByteBuffer.wrap(msg.getBytes());
//                        sc.write(bb);
//                    }
//
//                }
//            }
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }

    private void sendToclient(String msg, SocketChannel self) throws IOException {
        for (SelectionKey key:selector.keys()){
            Channel targetChannel = key.channel();
            if (targetChannel instanceof SocketChannel && targetChannel != self){
                //转型
                SocketChannel dest = (SocketChannel)targetChannel;
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                dest.write(byteBuffer);

            }

        }
    }
}
